package meituan.food;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ifast.demo.domain.MeituanFoodDO;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.XpathSelector;

/**
 * @author code4crafter@gmail.com <br>
 */
public class MeituanFoodProcessor implements PageProcessor {
	
	public static String key = "dbKey";
	
    @Override
    public void process(Page page) {
       // List<String> requests = page.getHtml().links().regex(".*article.*").all();
       String shop = page.getHtml().select(new XpathSelector("script")).all().get(14);
       if(StringUtils.isNotBlank(shop)){
    	   shop = StringUtils.substringBetween(shop,"window._appState =", ";</script>"); 
    	   
    	   JSONObject obj = JSON.parseObject(shop);
    	   System.out.println(obj.getJSONObject("poiLists").get("totalCounts"));
    	   JSONArray shoparr = obj.getJSONObject("poiLists").getJSONArray("poiInfos");
    	   List<MeituanFoodDO> foodShops = Lists.newArrayList();
    	   for(int i=0,total = shoparr.size();i<total;i++){ 
    		   MeituanFoodDO stu1=JSON.parseObject(shoparr.getString(i).toString(),MeituanFoodDO.class);
    		   System.out.println(stu1);
    		   foodShops.add(stu1); 
    	   } 
    	   page.putField(key, foodShops);
       } 
    }

    @Override
    public Site getSite() {
        return Site.me().setDomain("chifeng.meituan.com");
    }

    public static void main(String[] args){
    	
    	int total = 324;
    	int i = 1;
    	List<String> urls = new ArrayList<String>();
    	while(total >=0 ){
    		urls.add("https://chifeng.meituan.com/meishi/b2368/pn"+i+"/");
    		i++;
    		total -= 15;
    	}
    	//Spider.create(new MeituanProcessor()).addUrl(urls.toArray(new String[urls.size()])).run();
        Spider.create(new MeituanFoodProcessor()).addUrl("https://chifeng.meituan.com/meishi/b2368/pn1/").run();
        
    }

}
